<template>
  <!-- 添加请购  -->
  <div class="contractInfo box">
    <el-card
      shadow="never"
      :header="titleMap[mode]"
      class="item-background"
      style="width: 100%"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="addForm"
        label-width="auto"
        label-position="right"
      >
        <el-form-item label="标题" prop="title" style="width: 100%">
          <el-input
            v-model="form.title"
            clearable
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-select
            v-model="form.departmentId"
            placeholder="请选择"
            @change="selectDeaprtment"
            style="width: 100%"
          >
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请购人" prop="adminId">
          <el-select
            v-model="form.adminId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经办人" prop="operatorName">
          <el-input
            v-model="form.operatorName"
            clearable
            @click="selectOpertaor"
            placeholder="请选择经办人"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="请购时间" prop="requisitionTime">
          <el-date-picker
            v-model="form.requisitionTime"
            type="date"
            placeholder="请购时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item></el-form-item>
        <el-form-item label="请购物品" prop="warehouseId" request>
          <el-button type="primary" plain @click="showSelectGoods"
            >选择物品</el-button
          >
        </el-form-item>

        <el-form-item label="请购明细" prop="adminId" style="width: 100%">
          <sc-form-table
            ref="table"
            v-model="goodsList"
            :hideAdd="true"
            placeholder="暂无数据"
            stripe
            border
          >
            <el-table-column
              label="物品名称"
              prop="name"
              min-width="100"
            ></el-table-column>
            <el-table-column
              label="规格型号"
              prop="spuSpecification"
              min-width="100"
            ></el-table-column>
            <!-- <el-table-column
              label="价格(元)"
              prop="price"
              width="150"
            ></el-table-column> -->
            <el-table-column label="数量" prop="productBuyNum" width="250">
              <template #default="scope">
                <el-input
                  v-model="scope.row.productBuyNum"
                  clearable
                  placeholder="请输入请购数量"
                  oninput="value=value.replace(/^\D*([0-9]\d*)?.*$/,'$1')"
                  @blur="scope.row.productBuyNum = $event.target.value"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="单位"
              prop="productUnitName"
              width="100"
            ></el-table-column>
          </sc-form-table>
        </el-form-item>
        <el-form-item label="备注" style="width: 100%">
          <el-input
            type="textarea"
            v-model="form.remark"
            rows="3"
            clearable
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 审核流程项 -->
      <check-form-item
        ref="checkFormItem"
        @setCheckConfig="setCheckConfig"
        :field="this.form"
        :checkType="checkType"
        v-show="$route.query.mode == 'add'"
      ></check-form-item>

      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </el-card>

    <!-- 选择经办人 -->
    <select-user ref="selectUser" @setUser="setOpertaor"></select-user>

    <!-- 选择物品 -->
    <select-goods ref="selectGoods" @selectGoods="selectGoods"></select-goods>
  </div>
</template>
<script>
import selectUser from "@/components/selectUser"
import selectGoods from "../../components/selectGoods"
import checkFormItem from "@/components/checkProcess/checkFormItem.vue"
export default {
  name: "addPurchaseRequest",
  data () {
    return {
      checkType: 22, //工作流的类型
      mode: this.$route.query.mode,
      titleMap: {
        add: "添加",
        edit: "编辑",
      },
      isSaveing: false,
      attrObj: null,
      form: {
        adminId: "", //请购人id
        departmentId: "", //部门id
        operatorId: "", //经办人id
        operatorName: "", //经办人
        title: "",
        // requisitionTime: '',//请购时间
        remark: "", //备注
        exempt: "", //是否免审
        requisitionProductList: [], //请购产品
        workflowJsonList: [],
      },

      departmentList: [], //部门列表
      userList: [], //用户列表
      goodsList: [], //请购物品列表
      userInfo: {},
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
        ],
        departmentId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
        adminId: [
          {
            required: true,
            message: "请选择请购人",
            trigger: "change",
          },
        ],
        requisitionTime: [
          {
            type: "date",
            required: true,
            message: "请选择请购时间",
            trigger: "change",
          },
        ],
        operatorName: [
          {
            required: true,
            message: "请选择经办人",
            trigger: "change",
          },
        ],
      },
    }
  },
  components: {
    selectUser,
    selectGoods,
    checkFormItem,
  },
  mounted () {
    this.userInfo = this.$TOOL.data.get("USER_INFO")
    this.form.adminId = this.userInfo.userId
    if (this.$route.query.mode == "edit") this.getDetail()
    this.getDepartmentList()
    this.getUserList(this.userInfo.departmentId)
  },
  methods: {
    // 审批流配置
    setCheckConfig (list, exempt) {
      this.form.workflowJsonList = list
      this.form.exempt = exempt
    },

    // 获取详情
    async getDetail () {
      let param = {
        limit: 1000,
        page: 1,
        id: this.$route.query.id,
      }
      let { data } = await this.$API.purchase.getPurchaseRequestList.get(
        param
      )
      this.form = data[0]
      this.goodsList = data[0].requisitionProductList
      console.log(data)
    },

    // 获取部门
    async getDepartmentList () {
      let { data } = await this.$API.department.getDepartmentList.get()
      this.departmentList = data
      this.form.departmentId = this.userInfo.departmentId
    },

    // 获取用户列表
    async getUserList (id) {
      let param = {
        limit: 1000,
        page: 1,
        departmentId: id,
      }
      let { data } = await this.$API.user.getUserList.get(param)
      this.userList = data
      // this.form.adminId = this.userInfo.userId
    },

    // 选择部门
    selectDeaprtment (id) {
      this.form.adminId = " "
      this.getUserList(id)
    },

    // 显示物品选择列表
    showSelectGoods () {
      this.$refs.selectGoods.open()
    },

    // 请购物品列表
    selectGoods (list) {
      this.goodsList = [...this.goodsList, ...list]
    },

    // 选择经办人
    selectOpertaor () {
      this.$refs.selectUser.open(1)
    },

    setOpertaor (data) {
      this.form.operatorId = data.id
      this.form.operatorName = data.name
    },

    // 添加
    save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          if (this.goodsList.length == 0) {
            this.$message.error("请选择请购物品")
            return
          }
          console.log(this.form)
          console.log(this.goodsList)

          let noNum = false
          let obj = null
          let list = []
          this.goodsList.map((item) => {
            obj = {
              productSpuId: item.id,
              productBuyNum: item.productBuyNum,
              price: item.price,
              productName: item.name,
              specificationName: item.spuSpecification,
              unitId: item.unitId,
            }
            list.push(obj)
            if (obj.productBuyNum == "") {
              noNum = true
              this.$message.error(
                `请输入${obj.productName}的数量`
              )
            }
          })
          this.form.requisitionProductList = list
          if (noNum) return

          let res = null
          let mode = this.$route.query.mode
          this.isSaveing = true
          if (mode == "add") {
            res = await this.$API.purchase.addPurchaseRequest.post(
              this.form
            )
          } else if (mode == "edit") {
            delete this.form.createTime
            delete this.form.deleted
            delete this.form.state
            res =
              await this.$API.purchase.updatePurchaseRequest.post(
                this.form
              )
          }
          this.isSaveing = false
          if (res.code == 200) {
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: "/goods/purchaseRequest",
            })
            this.$message.success("操作成功")
          }
        }
      })
    },
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: "/goods/purchaseRequest",
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  margin: 10px;
}
.el-form {
  // width: 100%;
  padding: 30px;
  background: #fff;
}

.button {
  margin-top: 50px;
}
</style>
